package com.ljh.mall.service.impl;

import com.alibaba.fastjson.JSON;
import com.ljh.common.constant.CartConstant;
import com.ljh.common.utils.R;
import com.ljh.common.vo.MemberVO;
import com.ljh.mall.controller.CartController;
import com.ljh.mall.feign.ProductFeignService;
import com.ljh.mall.lnterceptor.AuthInterceptor;
import com.ljh.mall.service.ICartService;
import com.ljh.mall.vo.Cart;
import com.ljh.mall.vo.CartItem;
import com.ljh.mall.vo.SkuInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author ：刘剑鸿
 * @date ：Created in 2023/4/15 15:21
 * @description：
 * @modified By：
 * @version: $
 */
@Service
public class CartServiceImpl implements ICartService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    @Override
    public Cart getCartList() {
        BoundHashOperations<String, Object, Object> operations = getCartKeyOperation();
        Set<Object> keys = operations.keys();
        Cart cart = new Cart();
        List<CartItem> list = new ArrayList<>();
        for (Object k : keys) {
            String key = (String) k;
            Object o = operations.get(key);
            String json = (String) o;
            CartItem item = JSON.parseObject(json, CartItem.class);
            list.add(item);
        }
        cart.setItems(list);
        return cart;
    }

    @Override
    public CartItem addCarts(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartKeyOperation = getCartKeyOperation();
        Object o = cartKeyOperation.get(skuId.toString());
        if (o != null){
            String json = (String) o;
            CartItem iten = JSON.parseObject(json, CartItem.class);
            iten.setCount(iten.getCount()+num);
            cartKeyOperation.put(skuId.toString(),JSON.toJSONString(iten));
            return iten;
        }
        CartItem item = new CartItem();
        // 调用商品信息
        R info = productFeignService.info(skuId);
        SkuInfoVo vo = (SkuInfoVo)info.get("skuInfoJSON");
        item.setCheck(true);
        item.setCount(num);
        item.setPrice(vo.getPrice());
        item.setImage(vo.getSkuDefaultImg());
        item.setSkuId(skuId);
        item.setTitle(vo.getSkuTitle());
        // 获取商品的销售属性
        List<String> skuSaleAttrs = productFeignService.getSkuSaleAttrs(skuId);
        item.setSkuAttr(skuSaleAttrs);
        //把数据存储在Redis 中
        String string = JSON.toJSONString(item);
        cartKeyOperation.put(skuId.toString(),string);


        return item;
    }

    /**
     * 异步编排
     * @param skuId
     * @param num
     * @return
     */
    @Override
    public CartItem addCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> hashOperations =getCartKeyOperation();
        Object o = hashOperations.get(skuId.toString());
        if (o != null){
            String json = (String) o;
            CartItem item = JSON.parseObject(json, CartItem.class);
            item.setCount(item.getCount()+num);
            hashOperations.put(skuId.toString(),JSON.toJSONString(item));
            return item;
        }
        CartItem item = new CartItem();
        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
            R info = productFeignService.info(skuId);
//            System.out.println("数据"+JSON.toJSONString(info));
            String skuInfoJSON = (String) info.get("skuInfoJSON");
            SkuInfoVo vo = JSON.parseObject(skuInfoJSON, SkuInfoVo.class);
            item.setCheck(true);
            item.setCount(num);
            item.setPrice(vo.getPrice());
            item.setImage(vo.getSkuDefaultImg());
            item.setSkuId(skuId);
            item.setTitle(vo.getSkuTitle());
            item.setSpuId(vo.getSpuId());
            System.out.println("数据item"+JSON.toJSONString(item));
        }, executor);

        CompletableFuture<Void> voidCompletableFuture1 = CompletableFuture.runAsync(() -> {
            List<String> skuSaleAttrs = productFeignService.getSkuSaleAttrs(skuId);
            item.setSkuAttr(skuSaleAttrs);
        }, executor);

        CompletableFuture.allOf(voidCompletableFuture,voidCompletableFuture1).get();
        String string = JSON.toJSONString(item);
        hashOperations.put(skuId.toString(),string);
        return item;
    }

    /**
     * 获取当前登录用户选中的商品信息 购物车中
     * @return
     */
    @Override
    public List<CartItem> getUserCartItems() {
        BoundHashOperations<String, Object, Object> cartKeyOperation = getCartKeyOperation();
        List<Object> values = cartKeyOperation.values();
        List<CartItem> collect = values.stream().map(item -> {
            String json = (String) item;
            CartItem cartItem = JSON.parseObject(json, CartItem.class);
            return cartItem;
        }).filter(cartItem -> {
            return cartItem.isCheck();
        }).collect(Collectors.toList());

        return collect;
    }


    private BoundHashOperations<String, Object, Object> getCartKeyOperation(){

        MemberVO memberVO = AuthInterceptor.threadLocal.get();
        String cartKey = CartConstant.CART_PERFIX + memberVO.getId();
        System.out.println("cartKey"+cartKey);
        BoundHashOperations<String, Object, Object> hashOperations = redisTemplate.boundHashOps(cartKey);
//        redisTemplate.boundListOps()
        return hashOperations;
    }
}
